package com.xbongbong.pro.rabbitmq.help;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.function.Consumer;

/**
 * 使用WebClient发送http请求
 * 连接池配置见{@link com.xbongbong.pro.rabbitmq.config.WebClientConfig}
 * @author 李少杰
 * @version v1.0.0
 * @date 2021/9/15 15:53
 */
@Component
@SuppressWarnings("deprecation")
public class WebClientHelp {
    private static final Logger LOG = LoggerFactory.getLogger(WebClientHelp.class);
    @Resource
    private WebClient webClient;


    /**
     * 发送post请求
     * 失败补偿策略:
     *  1.发送失败后 最多重试3次
     *  2.起始补偿时间：3秒
     *  3.补偿倍数：2
     * @param url url
     * @param body 请求体
     * @param sign 签名
     */
    @Async(value = "webHookThreadPool")
    @Retryable(value = Exception.class, maxAttempts = 4, backoff = @Backoff(delay = 3000L, multiplier = 2))
    public void post(String url, String body, String sign) throws Exception {
        Consumer<HttpHeaders> headersConsumer = httpHeaders -> httpHeaders.add("sign", sign);
        Mono<String> resp = webClient.post()
                .uri(url)
                .headers(headersConsumer)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(Mono.just(body), String.class)
                .retrieve()
                .bodyToMono(String.class);
        LOG.info("ApiCallBack: url: " + url + " request: " + body + " response: " + resp.block());
    }
}
